// 动态生成飘动的爱心
function createFloatingHearts() {
    const container = document.getElementById('hearts-container');
    const colors = ['#D8A8C6', '#F8C3CD', '#8B4C7D'];
    
    setInterval(() => {
        const heart = document.createElement('div');
        heart.className = 'heart';
        heart.innerHTML = '<i class="fa fa-heart"></i>';
        
        // 随机位置和样式
        const size = Math.random() * 20 + 10;
        const left = Math.random() * 100;
        const color = colors[Math.floor(Math.random() * colors.length)];
        const delay = Math.random() * 3;
        const duration = Math.random() * 5 + 3;
        
        heart.style.left = `${left}%`;
        heart.style.bottom = '-20px';
        heart.style.fontSize = `${size}px`;
        heart.style.color = color;
        heart.style.animationDelay = `${delay}s`;
        heart.style.animationDuration = `${duration}s`;
        
        container.appendChild(heart);
        
        // 移除已完成动画的爱心
        setTimeout(() => {
            heart.remove();
        }, (delay + duration) * 1000);
    }, 800);
}

// 音乐控制功能
function setupAudioControls() {
    const audio = document.getElementById('background-music');
    const toggleBtn = document.getElementById('music-toggle');
    const volumeSlider = document.getElementById('volume-slider');
    const volumeContainer = document.getElementById('volume-slider-container');
    
    // 设置音量
    audio.volume = volumeSlider.value;
    
    // 音量控制
    volumeSlider.addEventListener('input', () => {
        audio.volume = volumeSlider.value;
    });
    
    // 音乐播放/暂停切换
    toggleBtn.addEventListener('click', () => {
        if (audio.paused) {
            playAudio();
        } else {
            pauseAudio();
        }
    });
    
    // 显示/隐藏音量控制
    toggleBtn.addEventListener('mouseenter', () => {
        volumeContainer.classList.add('visible');
    });
    
    volumeContainer.addEventListener('mouseenter', () => {
        volumeContainer.classList.add('visible');
    });
    
    document.addEventListener('click', (e) => {
        if (!toggleBtn.contains(e.target) && !volumeContainer.contains(e.target)) {
            volumeContainer.classList.remove('visible');
        }
    });
    
    // 播放音频函数
    function playAudio() {
        audio.play().then(() => {
            toggleBtn.innerHTML = '<i class="fa fa-pause"></i>';
            toggleBtn.classList.add('playing');
        }).catch(error => {
            console.log('无法自动播放音频，需要用户交互:', error);
            // 显示更明显的提示，引导用户点击播放
            showPlayPrompt();
        });
    }
    
    // 暂停音频函数
    function pauseAudio() {
        audio.pause();
        toggleBtn.innerHTML = '<i class="fa fa-music"></i>';
        toggleBtn.classList.remove('playing');
    }
    
    // 显示播放提示
    function showPlayPrompt() {
        // 添加更明显的提示，引导用户点击播放按钮
        toggleBtn.style.animation = 'playBtnPulse 1s infinite';
        
        // 创建临时提示文本
        let playHint = document.getElementById('play-hint');
        if (!playHint) {
            playHint = document.createElement('div');
            playHint.id = 'play-hint';
            playHint.textContent = '点击播放背景音乐';
            playHint.style.cssText = `
                position: fixed;
                bottom: 90px;
                right: 20px;
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 8px 12px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 99;
                white-space: nowrap;
            `;
            document.body.appendChild(playHint);
        }
        
        // 5秒后隐藏提示
        setTimeout(() => {
            toggleBtn.style.animation = '';
            if (playHint && playHint.parentNode) {
                playHint.parentNode.removeChild(playHint);
            }
        }, 5000);
    }
    
    // 添加空的updateProgress函数作为安全措施，防止任何可能的引用导致错误
    function updateProgress() {
        // 已移除进度条功能
        return;
    }
    
    // 尝试自动播放的多种方法
    function attemptAutoPlay() {
        // 方法1: 直接尝试播放
        const playPromise = audio.play();
        
        if (playPromise !== undefined) {
            playPromise.then(() => {
                console.log('音频自动播放成功');
                toggleBtn.innerHTML = '<i class="fa fa-pause"></i>';
                toggleBtn.classList.add('playing');
            }).catch(error => {
                console.log('首次尝试自动播放失败，尝试其他方法:', error);
                
                // 方法2: 使用用户交互的模拟（对于某些浏览器可能有效）
                setTimeout(() => {
                    const clickEvent = new MouseEvent('click', {
                        bubbles: true,
                        cancelable: true,
                        view: window
                    });
                    document.body.dispatchEvent(clickEvent);
                    
                    // 方法3: 监听任何可能的用户交互
                    const userInteractHandler = () => {
                        playAudio();
                        document.removeEventListener('click', userInteractHandler);
                        document.removeEventListener('touchstart', userInteractHandler);
                        document.removeEventListener('keydown', userInteractHandler);
                        document.removeEventListener('scroll', userInteractHandler);
                    };
                    
                    document.addEventListener('click', userInteractHandler, { once: true });
                    document.addEventListener('touchstart', userInteractHandler, { once: true });
                    document.addEventListener('keydown', userInteractHandler, { once: true });
                    document.addEventListener('scroll', userInteractHandler, { once: true });
                }, 100);
            });
        }
    }
    
    // 页面加载完成后立即尝试自动播放
    if (document.readyState === 'complete') {
        attemptAutoPlay();
    } else {
        window.addEventListener('load', attemptAutoPlay);
    }
}

// 设置图片查看器功能
function setupImageViewer() {
    // 创建图片查看器模态框
    const viewer = document.createElement('div');
    viewer.className = 'image-viewer';
    viewer.innerHTML = `
        <div class="image-viewer-content">
            <button class="image-viewer-close"><i class="fa fa-times"></i></button>
            <img id="viewer-image" src="" alt="放大图片">
        </div>
    `;
    document.body.appendChild(viewer);
    
    const viewerImage = document.getElementById('viewer-image');
    const closeButton = viewer.querySelector('.image-viewer-close');
    
    // 获取所有图片容器
    const photoContainers = document.querySelectorAll('.photo-container');
    
    // 为每个图片容器添加点击事件
    photoContainers.forEach(container => {
        container.addEventListener('click', () => {
            const img = container.querySelector('img');
            if (img) {
                viewerImage.src = img.src;
                viewerImage.alt = img.alt;
                viewer.classList.add('active');
                document.body.style.overflow = 'hidden'; // 防止背景滚动
            }
        });
    });
    
    // 关闭图片查看器
    function closeViewer() {
        viewer.classList.remove('active');
        document.body.style.overflow = '';
    }
    
    // 关闭按钮事件
    closeButton.addEventListener('click', closeViewer);
    
    // 点击模态框背景关闭
    viewer.addEventListener('click', (e) => {
        if (e.target === viewer) {
            closeViewer();
        }
    });
    
    // 按ESC键关闭
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && viewer.classList.contains('active')) {
            closeViewer();
        }
    });
}

// 初始化
function init() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            createFloatingHearts();
            setupAudioControls();
            setupModalEvents();
            setupEditableElements();
            setupImageViewer();
        });
    } else {
        // DOM已经加载完成
        createFloatingHearts();
        setupAudioControls();
        setupModalEvents();
        setupEditableElements();
        setupImageViewer();
    }
}

// 设置模态框事件
function setupModalEvents() {
    const modal = document.getElementById('response-modal');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');
    const closeModal = document.getElementById('close-modal');
    
    document.getElementById('accept-btn').addEventListener('click', () => {
        modalTitle.textContent = '感谢您的祝福';
        modalMessage.textContent = '我们期待在婚礼上与您共同分享这一幸福时刻！';
        modal.classList.remove('hidden');
    });
    
    document.getElementById('decline-btn').addEventListener('click', () => {
        modalTitle.textContent = '非常遗憾';
        modalMessage.textContent = '感谢您的回复，希望有机会能与您分享我们的喜悦。';
        modal.classList.remove('hidden');
    });
    
    closeModal.addEventListener('click', () => {
        modal.classList.add('hidden');
    });
    
    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.classList.add('hidden');
        }
    });
}

// 设置可编辑元素
function setupEditableElements() {
    // 允许用户编辑新人姓名、时间和地点
    const editableElements = ['bride-name', 'groom-name', 'wedding-date', 'wedding-location'];
    editableElements.forEach(id => {
        const element = document.getElementById(id);
        // 检查元素是否存在，避免空指针错误
        if (element) {
            element.setAttribute('contenteditable', 'true');
            element.style.cursor = 'text';
            element.addEventListener('mouseenter', () => {
                element.style.backgroundColor = 'rgba(216, 168, 198, 0.1)';
            });
            element.addEventListener('mouseleave', () => {
                element.style.backgroundColor = 'transparent';
            });
        }
    });
}

// 启动初始化
init();